package com.wits.qso.web.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.web.Servlets;

import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.FileUtil;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.common.utils.StringUtil;
import com.wits.platform.web.controller.BaseController;
import com.wits.platform.web.mvc.PageParam;
import com.wits.qso.entity.Course;
import com.wits.qso.entity.HWKAttachment;
import com.wits.qso.entity.Homework;
import com.wits.qso.entity.HomeworkH;
import com.wits.qso.entity.HomeworkHView;
import com.wits.qso.entity.MaterialD;
import com.wits.qso.entity.Student;
import com.wits.qso.entity.Teacher;
import com.wits.qso.service.CourseService;
import com.wits.qso.service.HomeworkHService;
import com.wits.qso.service.HomeworkService;
import com.wits.qso.service.StudentService;
import com.wits.qso.service.TeacherService;
import com.wits.qso.service.YearService;

@Controller
@RequestMapping(value = "qso/homeworkSubmit")
public class HomeworkController extends BaseController {

	/**
	 * 注入courseRegisterService
	 */
	@Autowired
	private HomeworkService homeworkService;
	@Autowired
	private StudentService sutdentService;
	@Autowired
	private CourseService courseService;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private HomeworkHService homeworkHService;
	@Autowired
	private YearService yearService = null;

	protected static final String ATTR_COURSE_TITLE = "courses";
	//protected static final String ATTR_MARTERIALD = "materialD";
	private static String ATTR_ATTACHMENT_NAME = "hwkAttachmentNames";
	private static String ATTR_ATTACHMENT_SIZE = "hwkAttachmentSizes";

	@RequestMapping(value = "/toList")
	public String toList() {
		return "qso/homeworkSubmit/list";
	}

	@RequestMapping(value = "/toSelect")
	public String toSelect() {
		return "qso/homeworkSubmit/select";
	}

	@RequestMapping(value = "/toCorrectList")
	public String toCorrectList() {
		return "qso/homeworkSubmit/correctList";
	}

	/**
	 * 加载布置的作业视图列表页面
	 * 
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/listHWKHView")
	@ResponseBody
	public String selectHomeworkH(Model model,
			@ModelAttribute("page") PageParam page, HttpServletRequest req) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(
				req, "search_");

		// 根据当前登录的学生，找到对应的班级，查询所有布置给该班级的作业
		String userId = this.getCurrentUserId();
		Student stu = sutdentService.findByUserId(userId);
		String clsId = stu == null || stu.getClsId() == null ? "" : stu
				.getClsId();
		searchParams.put("cls_id", clsId);

//		List<HomeworkHView> crList = homeworkService
//				.findHomeworkHViews(searchParams);
		Page<HomeworkHView> crList = homeworkService.findHomeworkHViewPages(searchParams,page);
		return PageUtil.toAjaxPageResult(crList);
	}

	/**
	 * 学生端加载作业列表页面
	 * 
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/toStuList")
	@ResponseBody
	public String toStuList(Model model, @ModelAttribute("page") PageParam page,
			HttpServletRequest req) {
		return list(model,page,req,"isStudent");
	}
	/**
	 * 老师端查询作业提交列表
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/toTeaList")
	@ResponseBody
	public String toTeaList(Model model, @ModelAttribute("page") PageParam page,
			HttpServletRequest req) {
		return list(model,page,req,"isTeacher");
	}
	/**
	 * 查询作业提交列表
	 * @param model
	 * @param page
	 * @param req
	 * @param tag 标记
	 * @return
	 */
	private String list(Model model, @ModelAttribute("page") PageParam page,
			HttpServletRequest req,String tag) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(
				req, "search_");
		/**
		 * 学生端，只查询当前登录学生所提交的作业
		 */
		if("isStudent".equals(tag)){
			searchParams.put(SearchFilter.Operator.EQ+"_student.stuUserId", this.getCurrentUserId());
		}
		/**
		 * 老师端，只查询当前登录老师可以批改的作业
		 */
		if("isTeacher".equals(tag)){
			String status=req.getParameter("hwkStatus")==null?"":req.getParameter("hwkStatus");
			if(!"".equals(status)){
				searchParams.put(SearchFilter.Operator.EQ+"_hwkStatus", status);
			}
			searchParams.put(SearchFilter.Operator.EQ+"_teacher.terUserId", this.getCurrentUserId());
		}
		
		Page<Homework> crList = homeworkService.findPage(Homework.class,
				searchParams, page);
		return PageUtil.toAjaxPageResult(crList);
	}
	/**
	 * 加载记录查看页面
	 * 
	 * @param model
	 * @param viewType
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/view/{viewType}")
	public String toView(Model model, @PathVariable String viewType,
			@RequestParam String id) {
		if (ViewType.Add.getView().equals(viewType)) {
			model.addAttribute(WebConstants.COMMAND, new Homework());
		} else {
			model.addAttribute(WebConstants.COMMAND, homeworkService.getOne(id));
		}
		model.addAttribute("viewType", viewType);
		return "qso/homeworkSubmit/form";
	}

	/**
	 * 保存提交的新增或修改记录
	 * 
	 * @param model
	 * @param command
	 * @param viewType
	 * @param result
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/save", method = { RequestMethod.POST })
	@ResponseBody
	public Object save(Model model,
			@ModelAttribute("command") @Valid Homework command,
			@RequestParam String viewType, BindingResult result,
			HttpServletRequest req,HttpSession session) {
		List<HWKAttachment> hwkAttachmentList=new ArrayList<HWKAttachment>();
		
//		HttpSession session=req.getSession();
		List<String> fileNameList=(List<String>) session.getAttribute(ATTR_ATTACHMENT_NAME);
		List<Long> fileSizeList=(List<Long>) session.getAttribute(ATTR_ATTACHMENT_SIZE);
		
		
		if(fileNameList==null){
			session.removeAttribute( ATTR_ATTACHMENT_NAME );
			session.removeAttribute( ATTR_ATTACHMENT_SIZE );
			return ajaxDoneError( "请先上传附件" );
		}
		if (result.hasErrors()) {
			model.addAttribute(WebConstants.COMMAND, command);
			return toView(model, viewType, command.getId());
		}

		if (ViewType.Add.getView().equals(viewType)) {
			command.setDateCre(new Date());
			command.setUserCre(getCurrentUserId());
			for(int i=0;i<fileNameList.size();i++){
				HWKAttachment hwkFile=new HWKAttachment();
				hwkFile.setDateCre(new Date());
				hwkFile.setUserCre(this.getCurrentUserId());
				
				hwkAttachmentList.add(hwkFile);
			}
		} else {
			command.setDateUpd(new Date());
			command.setUserUpd(getCurrentUserId());
			
			List<HWKAttachment> tmpList=command.getHwkAttachmentList();
			if(tmpList!=null){
				hwkAttachmentList.addAll(tmpList);
				for(int i=0;i<hwkAttachmentList.size();i++){
					HWKAttachment hwkFile=hwkAttachmentList.get(i);
					hwkFile.setDateUpd(new Date());
					hwkFile.setUserUpd(this.getCurrentUserId());
				}
			}else{
				for(int i=0;i<fileNameList.size();i++){
					HWKAttachment file=new HWKAttachment();
					file.setDateCre(new Date());
					file.setUserCre(this.getCurrentUserId());
					hwkAttachmentList.add(file);
				}
			}
		}
		try {
			// 学生
			Student student = sutdentService.findByUserId(getCurrentUserId());
			command.setStudent(student);
			// 课程
			String courseId = req.getParameter("courseId");
			Course course = courseService.getOne(courseId);
			command.setCourse(course);
			// 老师
			String teacherId = req.getParameter("teacherId");
			Teacher teacher = teacherService.getOne(teacherId);
			command.setTeacher(teacher);
			// 布置的作业
			String homeworkHId = req.getParameter("homeworkHId");
			HomeworkH homeworkH = homeworkHService.getOne(homeworkHId);
			command.setHomeworkH(homeworkH);
			
			Homework homework=homeworkService.save(command);
			
			// 上传的作业附件
			if(fileNameList!=null && fileNameList.size()>0 
					&&fileSizeList!=null && fileSizeList.size()>0){
				for (int i = 0; i < hwkAttachmentList.size(); i++) {
					logger.info( " save materialD {}", command );
					HWKAttachment hwkAttachment=hwkAttachmentList.get(i);
					String fileName=fileNameList.get(i);

					hwkAttachment.setNewName(fileName);
					hwkAttachment.setOldName(fileName);
					hwkAttachment.setFilePath(fileNameList.get(i) );
					hwkAttachment.setFileSize((int)(fileSizeList.get(i).floatValue() / 1024 / 1024));
					hwkAttachment.setHomework(homework);
					hwkAttachment.setFileUri( "download/homework/" + fileNameList.get(i));
					
					homeworkService.saveOneAttachment( hwkAttachment );
				}
				session.removeAttribute( ATTR_ATTACHMENT_NAME );
				session.removeAttribute( ATTR_ATTACHMENT_SIZE );

				return ajaxDoneSuccess( this.getText( "save.success" ) );
			}else{
				session.removeAttribute( ATTR_ATTACHMENT_NAME );
				session.removeAttribute( ATTR_ATTACHMENT_SIZE );
				return ajaxDoneError( "请先上传附件" );
			}
		} catch (Exception e) {
			return ajaxDoneError(this.getText("save.failed"), e);
		}
	}

	/**
	 * 作业缴交
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/doSubmit")
	@ResponseBody
	public Object doSubmit(String ids) {
		boolean hasSuccessed = true;
		for (String id : Arrays.asList(StringUtil.split(ids, ","))) {
			try {
				boolean tmp = homeworkService.submitHomework(id);
				hasSuccessed = hasSuccessed && tmp;
			} catch (Exception e) {
				e.printStackTrace();
				hasSuccessed = false;
			}
		}
		if (hasSuccessed) {
			return ajaxDoneSuccess("缴交作业成功");
		} else {
			return ajaxDoneError("缴交作业失败");
		}
	}

	/**
	 * 加载作业批改页面
	 * 
	 * @param model
	 * @param viewType
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/toCorrectHWKView")
	public String toCorrectHWKView(Model model, @RequestParam String id) {
		model.addAttribute(WebConstants.COMMAND, homeworkService.getOne(id));
		return "qso/homeworkSubmit/correctForm";
	}

	/**
	 * 批改缴交的作业，评分，评语
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/doCorrect", method = { RequestMethod.POST })
	@ResponseBody
	public Object doAgree(Model model,
			@ModelAttribute("command") @Valid Homework command,
			BindingResult result, HttpServletRequest req) {
		boolean res=homeworkService.correctHomework(command);
		if (res) {
			return ajaxDoneSuccess("成功");
		} else {
			return ajaxDoneError("失败");
		} 
	}

	/**
	 * 删除记录
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(String ids) {
		boolean hasSusscesed = false;
		boolean hasErrored = false;

		for (String id : Arrays.asList(StringUtil.split(ids, ","))) {
			try {
				homeworkService.delete(id);
				hasSusscesed = true;
			} catch (Exception e) {
				hasErrored = true;
			}
		}

		if (hasSusscesed) {
			if (hasErrored) {
				return ajaxDoneError("有些被引用的记录无法删除");
			} else {
				return ajaxDoneSuccess(this.getText("delete.success"));
			}
		} else {
			return ajaxDoneError("所选记录已被引用, 无法删除");
		}
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/upload")
	public void upload(HttpServletRequest request,
			@RequestParam(value = "hwkAttachment") MultipartFile attachment,
			HttpSession session) {
		if (null != attachment) {
			logger.info("{}, {}", attachment.getSize(),
					attachment.getOriginalFilename());

			List<String> fileNameList = (List<String>) session
					.getAttribute(ATTR_ATTACHMENT_NAME);
			List<Long> fileSizeList = (List<Long>) session
					.getAttribute(ATTR_ATTACHMENT_SIZE);
			if (fileNameList == null || fileSizeList == null
					|| fileNameList.size() == 0 || fileSizeList.size() == 0) {
				fileNameList = new ArrayList<String>();
				fileSizeList = new ArrayList<Long>();
			}
			fileNameList.add(attachment.getOriginalFilename());
			fileSizeList.add(attachment.getSize());
			session.setAttribute(ATTR_ATTACHMENT_NAME, fileNameList);
			session.setAttribute(ATTR_ATTACHMENT_SIZE, fileSizeList);
			try {
				FileUtil.upload(attachment, request.getSession()
						.getServletContext().getRealPath("/")
						+ "download/homework/",
						attachment.getOriginalFilename());
			} catch (Throwable cause) {
				logger.error(cause.getMessage(), cause);
				session.removeAttribute(ATTR_ATTACHMENT_NAME);
				session.removeAttribute(ATTR_ATTACHMENT_SIZE);
			}
		}
	}

	@RequestMapping(value = "/download")
	public void download(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "hwkAttachmentId") String hwkAttachmentId) {
		String basePath = request.getSession().getServletContext()
				.getRealPath("/");
		String contentType = "application/octet-stream";
		HWKAttachment hwkAttachment = homeworkService
				.getOneAttachment(hwkAttachmentId);
		Map<String, String> map = new HashMap<String, String>();
		map.put("filePath", hwkAttachment.getFileUri());
		map.put("originalName", hwkAttachment.getOldName());

		FileUtil.download(response, basePath, contentType, map);
	}

	@RequestMapping(value = "/deleteHWKAttachment")
	@ResponseBody
	public Object deleteHWKAttachment(HttpServletRequest request, @RequestParam(value = "id")
	String id) {
		HWKAttachment hwkAttachment = homeworkService.getOneAttachment(id);
		boolean flag=homeworkService.deleteOneAttachment(id);
		if (flag) {
			File f = new File( request.getSession().getServletContext().getRealPath( "/" ) + "upload/homework/" + hwkAttachment.getFilePath());
			f.delete();
		}
		return "true";
	}
}
